<template>
  <div class="profile-container">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="user-info">
            <div class="avatar-container">
              <el-avatar :size="100" :src="userInfo.avatar">
                {{ userInfo.nickname?.charAt(0)?.toUpperCase() }}
              </el-avatar>
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
              >
                <el-button type="primary" link>更换头像</el-button>
              </el-upload>
            </div>
            <h3 class="username">{{ userInfo.username }}</h3>
            <p class="role">{{ userInfo.role }}</p>
          </div>
          <el-divider />
          <div class="info-list">
            <p><el-icon><User /></el-icon> 昵称：{{ userInfo.nickname }}</p>
            <p><el-icon><Phone /></el-icon> 手机：{{ userInfo.phone }}</p>
            <p><el-icon><Message /></el-icon> 邮箱：{{ userInfo.email }}</p>
            <p><el-icon><Clock /></el-icon> 创建时间：{{ userInfo.createTime }}</p>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧信息编辑卡片 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-tabs v-model="activeTab">
                <el-tab-pane label="基本信息" name="basic">
                  <template #label>
                    <span><el-icon><Edit /></el-icon> 基本信息</span>
                  </template>
                </el-tab-pane>
                <el-tab-pane label="修改密码" name="password">
                  <template #label>
                    <span><el-icon><Lock /></el-icon> 修改密码</span>
                  </template>
                </el-tab-pane>
              </el-tabs>
            </div>
          </template>

          <!-- 基本信息表单 -->
          <el-form
            v-if="activeTab === 'basic'"
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="100px"
          >
            <el-form-item label="用户名">
              <el-input v-model="userInfo.username" disabled />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="basicForm.nickname" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="basicForm.phone" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="basicForm.email" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdateBasic">保存修改</el-button>
            </el-form-item>
          </el-form>

          <!-- 修改密码表单 -->
          <el-form
            v-else
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleUpdatePassword">
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Phone, Message, Clock, Edit, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()
const userInfo = userStore.userInfo

// 当前激活的标签页
const activeTab = ref('basic')

// 基本信息表单
const basicFormRef = ref(null)
const basicForm = reactive({
  nickname: userInfo.nickname,
  phone: userInfo.phone,
  email: userInfo.email
})

const basicRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 密码表单
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 头像上传前的处理
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }

  if (isJPG && isLt2M) {
    // 这里应该调用上传API
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      userInfo.avatar = reader.result
      ElMessage.success('头像上传成功')
    }
  }
  return false
}

// 更新基本信息
const handleUpdateBasic = async () => {
  if (!basicFormRef.value) return
  
  try {
    await basicFormRef.value.validate()
    // 这里应该调用API更新用户信息
    Object.assign(userInfo, basicForm)
    ElMessage.success('信息更新成功')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 更新密码
const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    // 这里应该调用API更新密码
    ElMessage.success('密码修改成功')
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.profile-card {
  text-align: center;
}

.avatar-container {
  margin: 20px 0;
}

.avatar-uploader {
  margin-top: 10px;
}

.username {
  margin: 10px 0;
  font-size: 20px;
}

.role {
  color: #909399;
  font-size: 14px;
}

.info-list {
  text-align: left;
  padding: 0 20px;
}

.info-list p {
  margin: 10px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.info-list .el-icon {
  color: #909399;
}

:deep(.el-tabs__nav-wrap::after) {
  display: none;
}
</style> 